import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 从数据库表反射出实体类，自动生成实体类
 *
 * @author lry
 */
public class GenEntityMysql {

    private String packageOutPath = "com.gjintel.test";//指定实体生成所在包的路径
    private String authorName = "wwang";//作者名字
    private String[] colnames; // 数据库列名数组
    private String tablename;//数据库表名
    private List<String> comments;//表字段注释

    private String[] mColnames; // 实体类列名数组
    private String mTablename;//实体类表名

    private String[] colTypes; //列名类型数组
    private int[] colSizes; //列名大小数组
    private boolean f_util = false; // 是否需要导入包java.util.*
    private boolean f_sql = false; // 是否需要导入包java.sql.*
    private boolean f_jpa = true; // 是否需要生成基于注解的JPA实体对象
    private boolean f_math = false; // 是否需要生成java.math.*

    //数据库连接
    private static final String URL = "jdbc:mysql://192.168.1.212:3306/e_auction";
    private static final String NAME = "root";
    private static final String PASS = "test";
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    /*
     * 构造函数
     */
    public GenEntityMysql() {
        List<String> list = getTableName();
        //循环所有的表
        for (int p = 0; p < list.size(); p++) {
            tablename = list.get(p);
            mTablename = parseTableName(list.get(p));
            comments=getColumnCommentByTableName(tablename);
            //创建连接
            Connection con;
            //查要生成实体类的表
            String sql = "select * from " + tablename;
            PreparedStatement pStemt = null;
            try {
                try {
                    Class.forName(DRIVER);
                } catch (ClassNotFoundException e1) {
                    e1.printStackTrace();
                }
                con = DriverManager.getConnection(URL, NAME, PASS);
                pStemt = con.prepareStatement(sql);
                ResultSetMetaData rsmd = pStemt.getMetaData();
                int size = rsmd.getColumnCount();    //统计列
                colnames = new String[size];
                mColnames = new String[size];
                colTypes = new String[size];
                colSizes = new int[size];
                //循环表字段
                for (int i = 0; i < size; i++) {
                    colnames[i] = rsmd.getColumnName(i + 1);
                    mColnames[i] = parseColname(rsmd.getColumnName(i + 1));
                    colTypes[i] = rsmd.getColumnTypeName(i + 1);
                    if (colTypes[i].equalsIgnoreCase("datetime")
                            || colTypes[i].equalsIgnoreCase("date")
                            || colTypes[i].equalsIgnoreCase("timestamp")) {
                        f_util = true;
                    }
                    if (colTypes[i].equalsIgnoreCase("image")
                            || colTypes[i].equalsIgnoreCase("text")
                            || colTypes[i].equalsIgnoreCase("Blob")) {
                        f_sql = true;
                    }
                    if (colTypes[i].equalsIgnoreCase("decimal")) {
                        f_math = true;
                    }
                    colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
                }

                String content = parse(mColnames, colTypes, colSizes);

                try {
                    File directory = new File("");
                    String outputPath = directory.getAbsolutePath() + "/src/main/java/" + this.packageOutPath.replace(".", "/") + "/" + mTablename + ".java";
                    FileWriter fw = new FileWriter(outputPath);
                    PrintWriter pw = new PrintWriter(fw);
                    pw.println(content);
                    pw.flush();
                    pw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                //			try {
                //				con.close();
                //			} catch (SQLException e) {
                //				// TODO Auto-generated catch block
                //				e.printStackTrace();
                //			}
            }
        }
        System.out.println("生成完毕！");
    }

    /**
     * 解析表名
     *
     * @param colname
     * @return
     */
    private static String parseColname(String colname) {
        colname = colname.toLowerCase();
        int index = 0;
        int count = 0;
        Pattern p = Pattern.compile("_");
        Matcher m = p.matcher(colname);
        while (m.find()) {
            count++;
        }

        List<Integer> indexList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            indexList.add(colname.indexOf("_", index));
            index = colname.indexOf("_", index) + 1;
        }

        for (Integer ind : indexList) {
            if (ind < colname.length()) {
                if (ind < colname.length()) {
                    if (ind < colname.length() - 1) {
                        String world = colname.substring(ind + 1, ind + 2);
                        StringBuffer sb = new StringBuffer(colname);
                        colname = sb.replace(ind + 1, ind + 2, world.toUpperCase()).toString();
                    }
                }
            }
        }
        //解决关键字 加_
        if (colname.endsWith("_")) {
            colname = colname.replace("_", "") + "_";
        } else {
            colname = colname.replace("_", "");
        }
        return colname;
    }

    /**
     * 解析表名
     *
     * @param tname
     * @return
     */
    private static String parseTableName(String tname) {
        tname = tname.replace("t_sys_", "");//去掉表名的t_sys_
        tname = tname.replace("T_SYS_", "");//去掉表名的T_SYS_

        tname = tname.replace("t_business_", "");//去掉表名的t_business_
        tname = tname.replace("T_BUSINESS_", "");//去掉表名的 T_BUSINESS_

        tname = tname.replace("t_base_", "");//去掉表名的 t_base_
        tname = tname.replace("T_BASE_", "");//去掉表名的 t_base_

        tname = tname.replace("t_biz_", "");//去掉表名的 t_biz
        tname = tname.replace("T_BIZ_", "");//去掉表名的 T_BIZ

        //开头有"t_" //去掉表名的t_
        if (tname.toLowerCase().startsWith("t_")) {
            StringBuffer sb = new StringBuffer(tname);
            tname = sb.replace(0, 2, "").toString();
        }


        tname = tname.toLowerCase();

        char[] ch = tname.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        tname = new String(ch);


        int index = 0;
        int count = 0;
        Pattern p = Pattern.compile("_");
        Matcher m = p.matcher(tname);
        while (m.find()) {
            count++;
        }

        List<Integer> indexList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            indexList.add(tname.indexOf("_", index));
            index = tname.indexOf("_", index) + 1;
        }

        for (Integer ind : indexList) {
            if (ind < tname.length() - 1) {
                String world = tname.substring(ind + 1, ind + 2);
                StringBuffer sb = new StringBuffer(tname);
                tname = sb.replace(ind + 1, ind + 2, world.toUpperCase()).toString();
            }
        }

        //解决关键字 加_
        if (tname.endsWith("_")) {
            tname = tname.replace("_", "") + "_";
        } else {
            tname = tname.replace("_", "");
        }

        return tname;
    }

    /**
     * Java方法 得到当前数据库下所有的表名
     */
    private List<String> getTableName() {
        List<String> list = new ArrayList<String>();
        try {
            DatabaseMetaData meta = DriverManager.getConnection(URL, NAME, PASS).getMetaData();
            ResultSet rs = meta.getTables(null, null, null, new String[]{"TABLE"});
            while (rs.next()) {
                list.add(rs.getString(3));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 功能：生成实体类主体代码
     *
     * @param colnames
     * @param colTypes
     * @param colSizes
     * @return
     */
    private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + this.packageOutPath + ";\r\n");
        sb.append("\r\n");

        //判断是否导入工具包
        if (f_util) {
            sb.append("import java.util.Date;\r\n");
        }
        if (f_sql) {
            sb.append("import java.sql.*;\r\n");
        }
        if (f_math) {
            sb.append("import java.math.*;\n");
        }

        //jpa
        if (f_jpa) {
            sb.append("import javax.persistence.Entity;\r\n");
            sb.append("import javax.persistence.GeneratedValue;\r\n");
            sb.append("import javax.persistence.GenerationType;\r\n");
            sb.append("import javax.persistence.Id;\r\n\r\n");
            sb.append("import javax.persistence.*;\r\n\r\n");
            sb.append("import org.hibernate.annotations.GenericGenerator;\r\n\r\n");
        }

        //注释部分
        sb.append("/**\r\n");
        sb.append(" * " + mTablename + " 实体类\r\n");
        sb.append(" * " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\r\n");
        sb.append(" * @author " + this.authorName + "\r\n");
        sb.append(" */ \r\n");

        if (f_jpa) {
            sb.append("@Entity\r\n");
            sb.append("@Table(name=\"" + tablename + "\")\r\n");
        }
        //实体部分
        sb.append("public class " + mTablename + "{\r\n\r\n");
        processAllAttrs(sb);//属性
        processAllMethod(sb);//get set方法
        sb.append("}\r\n");

        //System.out.println(sb.toString());
        return sb.toString();
    }

    /**
     * 功能：生成所有属性
     *
     * @param sb
     */
    private void processAllAttrs(StringBuffer sb) {
        for (int i = 0; i < mColnames.length; i++) {
            if(i==0){
                    sb.append("\t@Id\r\n");
                    sb.append("\t@GeneratedValue(generator = \"UIDGenerator\")\r\n");
                    sb.append("\t@GenericGenerator(name = \"UIDGenerator\", strategy = \"org.hibernate.id.UUIDHexGenerator\")\r\n");
            }else{
                sb.append("\t@Column(name=\"" + colnames[i] + "\")\r\n");
            }
            sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + mColnames[i] + ";//");

            //添加注释
            sb.append(comments.get(i)+"\r\n\n");
        }
        sb.append("\r\n");
    }

    /**
     * 功能：生成所有方法
     *
     * @param sb
     */
    private void processAllMethod(StringBuffer sb) {

        for (int i = 0; i < mColnames.length; i++) {

            if (f_jpa) {
                if (i == 0) {
                    sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(mColnames[i]) + "(){\r\n");
                } else {
                    sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(mColnames[i]) + "(){\r\n");
                }
            } else {
                sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(mColnames[i]) + "(){\r\n");
            }
            sb.append("\t\treturn " + mColnames[i] + ";\r\n");
            sb.append("\t}\r\n\r\n");
            sb.append("\tpublic void set" + initcap(mColnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " + mColnames[i] + "){\r\n");
            sb.append("\t\tthis." + mColnames[i] + "=" + mColnames[i] + ";\r\n");
            sb.append("\t}\r\n\r\n");
        }

    }

    /**
     * 功能：将输入字符串的首字母改成大写
     *
     * @param str
     * @return
     */
    private static String initcap(String str) {
        //str=str.toLowerCase();

        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        str = new String(ch);
        //str=parseColname(str);
        return str;
    }

    /**
     * 功能：获得列的数据类型
     *
     * @param sqlType
     * @return
     */
    private String sqlType2JavaType(String sqlType) {

        if (sqlType.equalsIgnoreCase("bit")) {
            return "Boolean";
        } else if (sqlType.equalsIgnoreCase("tinyint")) {
            return "Byte";
        } else if (sqlType.equalsIgnoreCase("smallint")) {
            return "Short";
        } else if (sqlType.equalsIgnoreCase("int") || sqlType.equalsIgnoreCase("INT UNSIGNED")) {
            //INT UNSIGNED无符号整形
            return "Integer";
        } else if (sqlType.equalsIgnoreCase("bigint")) {
            return "Long";
        } else if (sqlType.equalsIgnoreCase("float")) {
            return "Float";
        } else if (sqlType.equalsIgnoreCase("numeric")
                || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
                || sqlType.equalsIgnoreCase("smallmoney")
                || sqlType.equalsIgnoreCase("double")) {
            return "Double";
        } else if (sqlType.equalsIgnoreCase("decimal")) {
            return "BigDecimal";
        } else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
                || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
                || sqlType.equalsIgnoreCase("text")
                || sqlType.equalsIgnoreCase("varbinary")) {
            return "String";
        } else if (sqlType.equalsIgnoreCase("datetime")
                || sqlType.equalsIgnoreCase("date")
                || sqlType.equalsIgnoreCase("timestamp")) {
            return "Date";
        } else if (sqlType.equalsIgnoreCase("image")) {
            return "Blod";
        } else if (sqlType.equalsIgnoreCase("blob")) {
            return "Blob";
        } else if (sqlType.equalsIgnoreCase("longblob")) {
            return "byte[]";
        }
        return null;
    }


    /**
     * 获取表的字段注释
     * @param tableName 表名
     * @return
     * @throws Exception
     */
    public static List<String> getColumnCommentByTableName(String tableName){
        List<String> commet = new ArrayList<>();

        try {
            Connection conn = DriverManager.getConnection(URL, NAME, PASS);
            Statement stmt = conn.createStatement();

            ResultSet rs = stmt.executeQuery("show full columns from " + tableName);
            if (rs != null ) {
                while (rs.next()) {
                    //System.out.println("字段名称：" + rs.getString("Field") + "\t" + "字段注释：" + rs.getString("Comment"));
                    commet.add(rs.getString("Comment"));
                }
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return commet;
    }


    /**
     * 出口
     * TODO
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        new GenEntityMysql();


//        List<String> list = GenEntityMysql.getColumnCommentByTableName("act_evt_log");
//        for (String c:list) {
//            System.out.println("coment = " + c);
//        }

//		String test="t_auction_first_round_bid";
//		System.out.println("tname.startsWith(\"_\") = " + test.startsWith("t_"));
//
//
//		System.out.println(GenEntityMysql.parseTableName(test));


        // 可以用 StringBuilder 这个类，里面有一个接口replace，如下
//		StringBuilder sb = new StringBuilder("abcd");
//		sb.replace(1, 3, "测试是否替换指定的第二个元素");
//		System.out.println(sb.toString());


//		int index=0;
//		int count = 0;
//		Pattern p = Pattern.compile("_");
//		Matcher m = p.matcher(test);
//		while (m.find()) {
//			count++;
//		}
//		//System.out.println("---->"+count);
//
//		List<Integer> indexList=new ArrayList<>();
//		for (int i = 0; i < count; i++) {
//			indexList.add(test.indexOf("_",index));
//			index=test.indexOf("_",index)+1;
//		}
//
//		for (Integer ind:indexList) {
//			//System.out.println("ind =" + test.substring(ind+1,ind+2));
//			String world= test.substring(ind+1,ind+2);
//			test=test.replace(world,world.toUpperCase());
//		}
//		test=test.replace("_","");
//		System.out.println("test = " + test);

//		char[] ch = test.toCharArray();
//
//
//
//		if(ch[0] >= 'a' && ch[0] <= 'z'){
//			ch[0] = (char)(ch[0] - 32);
//		}
    }
}